package com.ruoyi.utils;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map;


/**
 * 常用工具类
 * 
 * @author 甘露华
 */
public class HttpUtils
{
    /**
     * get请求
     *
     * @return
     */
    public static JSONObject doGet(String url, Map<String, String> header) {

        CloseableHttpClient client = HttpClients.createDefault();
        try {
            // 发送get请求
            HttpGet request = new HttpGet(url);
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-Type", "application/json");

            if (header != null) {
                Iterator<Map.Entry<String, String>> it = header.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    request.setHeader(entry.getKey(), entry.getValue());
                }
            }
            HttpResponse response = client.execute(request);

            /** 请求发送成功，并得到响应 **/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /** 读取服务器返回过来的json字符串数据 **/
                String strResult = EntityUtils.toString(response.getEntity());

                return JSONObject.parseObject(strResult);
            }
        } catch (IOException e) {
            throw new ServiceException(e.getMessage());
        }

        return null;
    }

    /**
     * post请求(用于key-value格式的参数)
     *
     * @param url
     * @param params
     * @return
     */
    public static JSONObject doPost(String url, Map<String, Object> params) {

        CloseableHttpClient client = HttpClients.createDefault();
        params.put("param1", 1);

        BufferedReader in = null;
        try {
            // 定义HttpClient
            // 第一步：创建HttpClient对象
            client = HttpClients.createDefault();
            // 实例化HTTP方法
            HttpPost request = new HttpPost();
            request.setURI(new URI(url));

            // 设置参数 map转json
            String json = JSONObject.toJSONString(params);

            // 第四步：给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(json, "UTF-8");
            requestEntity.setContentEncoding("UTF-8");

            request.setEntity(requestEntity);

            HttpResponse response = client.execute(request);
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) { // 请求成功
                in = new BufferedReader(new InputStreamReader(response.getEntity()
                        .getContent(), "utf-8"));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }

                return JSONObject.parseObject(sb.toString());
            } else {
                throw new ServiceException("状态码：" + code);
            }
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    throw new ServiceException(e.getMessage());
                }
            }
        }
    }

    public static String urlDecode(String encode) {
        if (StringUtils.isEmpty(encode)) {
            return null;
        }
        try {
            String keyWord = URLDecoder.decode(encode, "utf-8");
            return keyWord;
        } catch (UnsupportedEncodingException e) {
            throw new ServiceException(e.getMessage());
        }
    }
}
